package com.lzh.excel.util;

import com.alibaba.fastjson.JSON;
import com.lzh.excel.exception.ErrorCode;
import com.lzh.excel.function.ThirdConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhehen.lu
 * @date 2025/8/3 14:35
 */
public class ExcelUtil {
    private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);

    public ExcelUtil() {
    }

    public static <T, K> void writeExcelToResponse(HttpServletResponse response, String fileName, T condition, K clazz, ThirdConsumer<OutputStream, T, K> consumer) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        try {
            OutputStream out = response.getOutputStream();
            Throwable throwable = null;

            try {
                String outFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
                response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + outFileName + ".xlsx");
                consumer.accept(out, condition, clazz);
                out.flush();
            } catch (Throwable throwable1) {
                throwable = throwable1;
                throw throwable1;
            } finally {
                if (out != null) {
                    if (throwable != null) {
                        try {
                            out.close();
                        } catch (Throwable var16) {
                            throwable.addSuppressed(var16);
                        }
                    } else {
                        out.close();
                    }
                }

            }
        } catch (IOException var19) {
            StringBuilder strBuff = new StringBuilder();
            strBuff.append(var19.getClass().getName()).append(":").append(var19.getMessage()).append("\n\t");
            StackTraceElement[] var7 = var19.getStackTrace();
            int var8 = var7.length;

            for(int var9 = 0; var9 < var8; ++var9) {
                StackTraceElement stet = var7[var9];
                strBuff.append(stet + "\n");
            }

            log.error(strBuff.toString());
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> map = new HashMap();
            map.put("code", ErrorCode.WRITE_DATA_TO_EXCEL_FAIL.getErrorCode());
            map.put("message", var19.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }

    }
}
